package cn.itcast.itcaststore.web.servlet;


import cn.itcast.itcaststore.domain.User;
import cn.itcast.itcaststore.service.Impl.IUserService;
import cn.itcast.itcaststore.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.ref.ReferenceQueue;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //get request checkCode
        String checkCode = request.getParameter("checkCode");

        //get client checkCode
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");

        //当用户back会出现空
        if (checkcode_server == null) {
            response.sendRedirect(request.getContextPath() + "/client/register.jsp");
            return;
        }

        //remove session
        session.removeAttribute("CHECKCODE_SERVER");


        User user = new User();

        Map<String, String[]> parameterMap = request.getParameterMap();
        UserService userService = new IUserService();

        try {
            BeanUtils.populate(user, parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //checkCode judgment
        if (checkcode_server.equalsIgnoreCase(checkCode)) {


            User resultUser = userService.getUser(user.getUsername());

            if (resultUser==null) {
                userService.addUser(user);
                response.sendRedirect(request.getContextPath() + "/client/registersuccess.jsp");
            }else {
                request.setAttribute("message","该用户名已经存在，请更换一个" );
                request.setAttribute("user",user );
                request.getRequestDispatcher("/client/register.jsp").forward(request,response);
            }
        } else {
            request.setAttribute("message","验证码错误！！！" );
            request.setAttribute("user",user );
            request.getRequestDispatcher("/client/register.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
